/**
 * 基于zepto|jquery的ajax方法封装
 * 阻止ajax重复提交
 * @param  {[type]} options [配置参数]
 * @return {[type]}         [ajax]
 * @author li.xiaomei@immomo.com
 */

(function(global, factory) {
  //AMD || CMD
  if (typeof define === 'function') {
    if (define.amd) {
      define(function() {
        return factory();
      });
    } else if (define.cmd) {
      define(function(require, exports, module) {
        module.exports = factory();
      });
    }
  } else if (typeof module === 'object' && typeof module.exports === 'object') {
    //CommonJS
    module.exports = factory();
  } else {
    global.moAjax = factory();
  }
}(typeof window !== 'undefined' ? window : this, function() {

  //检测是什么环境
  var isZepto = true;
  if (!Zepto && jQuery) {
    isZepto = false;
  } else if (!Zepto && !jQuery) {
    alert('请引入相应的zepto或jquery库');
    return false;
  }

  window.cacheContainer = {};

  function moAjax(options) {

    var defaults = {
      url: options.url,
      data: options.data || {},
      type: options.type || 'POST',
      dataType: options.dataType || 'json',
      jsonp: options.jsonp || 'callback',
      async: options.async || true,
      statusCode: options.statusCode || {},
      beforeSend: options.beforeSend || function() {},
      success: options.success || function() {},
      error: options.error || function() {},
      complete: options.complete || function() {}
    };

    var gid = defaults.url.split('?')[0];
    if (cacheContainer[gid]) {
      alert('请不要重复提交，请求正在处理中');
      return;
    }
    cacheContainer[gid] = true;

    var ajaxConfig = {
      data: defaults.data,
      type: defaults.type,
      dataType: defaults.dataType,
      cache: false,
      statusCode: defaults.statusCode,
      async: defaults.async,
      headers: defaults.headers,
      beforeSend: function(xhr) {
        defaults.beforeSend.call(xhr);
      },
      success: function(res, status, xhr) {
        defaults.success.call(xhr, res);
      },
      error: function(xhr, error) {
        defaults.error.call(xhr, error);
      },
      complete: function(xhr, error) {

        var gid = defaults.url.split('?')[0];
        delete cacheContainer[gid];
        defaults.complete.call(xhr, error);
      }
    };

    if (isZepto) {
      ajaxConfig.url = defaults.url;
      return $.ajax(ajaxConfig)
    }
    return $.ajax(defaults.url, ajaxConfig);

  }

  return moAjax;

}));
